<!--
 * @Author: dongdong.wu
 * @Date: 2020-08-07 15:15:29
 * @Description: Tree树形结构封装
-->
<template>
  <div class="we-tree_wrap">
    <el-input
      v-if="!$scopedSlots.select && isCondition"
      v-model="filterText"
      :placeholder="`请输入${placeholder || ''}`"
    />
    <!-- slot select 外部输入 -->
    <slot v-else name="select" />
    <div class="scroll">
      <el-tree
        :ref="treeRef"
        :data="data"
        :node-key="nodeKey"
        v-bind="$attrs"
        highlight-current
        :default-expanded-keys="defaultExpandedKeys"
        :props="defaultProps"
        :default-expand-all="defaultExpandAll"
        :expand-on-click-node="expandOnClickNode"
        :filter-node-method="filterNode"
        v-on="$listeners"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "WeTree",
  props: {
    treeRef: {
      type: String,
      default: "tree"
    },
    data: {
      // 展示的数据
      type: Array,
      default: () => {
        return [];
      }
    },
    placeholder: {
      type: String,
      default: ""
    },
    defaultProps: {
      // 自定义需要展示的字段（符合自己的字段）
      type: Object,
      default: () => {
        return {
          label: "name", // 显示的名称
          children: "childList" // 有子节点的属性
        };
      }
    },
    nodeKey: {
      // 节点的唯一标识
      type: String,
      default: "id"
    },
    defaultExpandedKeys: {
      // 默认展开节点的数值以nodeKey为标识的
      type: Array,
      default: () => {
        return [];
      }
    },
    defaultExpandAll: {
      // 是否默认全部打开
      type: Boolean,
      default: false
    },
    expandOnClickNode: {
      // 只有点击小图标才会收缩或者展开
      type: Boolean,
      default: false
    },
    isCondition: {
      // 是否给出输入
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      filterText: "" // 过滤数据
    };
  },
  watch: {
    filterText(val) {
      this.$refs[this.treeRef].filter(val);
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data[this.defaultProps.label].includes(value);
    },
    getAllKeys() {
      // 获取所有的check包含半选中的
      const halfCheck = this.$refs[this.treeRef].getHalfCheckedKeys();
      const checkKeys = this.$refs[this.treeRef].getCheckedKeys();
      return checkKeys.concat(halfCheck);
    },
    setChecked(key) {
      // 设置节点
      this.$refs[this.treeRef].setChecked(key, true, false);
    },
    getNoHalfCheckedKeys() {
      const checkKeys = this.$refs[this.treeRef].getCheckedKeys();
      return checkKeys;
    }
  }
};
</script>
<style lang="scss" scoped>
.we-tree_wrap {
  .scroll {
    max-height: 65vh;
    overflow-y: auto;
  }
  .el-tree {
    min-width: 100% !important;
    display: inline-block !important;
  }
  .el-input,
  .el-select {
    width: 100%;
  }
  .el-tree-node.is-current.is-focusable {
    color: var(--component-color);
  }
}
</style>
